package com.haoxuer.discover.pays.plugins.service.impl;

import com.haoxuer.discover.pays.api.domain.simple.WeiXinPaySimple;
import com.haoxuer.discover.pays.plugins.base.PaymentPlugin;
import com.haoxuer.discover.pays.plugins.domain.PayBack;
import com.haoxuer.discover.pays.plugins.domain.PayInfo;
import com.haoxuer.discover.pays.plugins.service.PayService;
import com.haoxuer.discover.user.word.AdaptiveRandomWordFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;


@Component
public class PayServiceImpl implements PayService {

  static Map<String, String> keys = new HashMap<>();

  static {
    keys.put("weixin", "weiXinPaymentPlugin");
    keys.put("weiapp", "weiAppPaymentPlugin");
    keys.put("wxapp", "weiAppPaymentPlugin");
    keys.put("wxapp_zg", "weiAppZGPaymentPlugin");
    keys.put("alipay", "alipayPaymentPlugin");
  }

  @Resource
  private List<PaymentPlugin> paymentPlugins = new ArrayList<PaymentPlugin>();

  @Resource
  private Map<String, PaymentPlugin> paymentPluginMap = new HashMap<String, PaymentPlugin>();

  public List<PaymentPlugin> getPushPlugins() {
    Collections.sort(paymentPlugins);
    return paymentPlugins;
  }

  @Override
  public PayBack pay(PayInfo payinfo) {
    PayBack result = new PayBack();
    String key = keys.get(payinfo.getPayType());
    PaymentPlugin pay = paymentPluginMap.get(key);
    if (pay == null) {
      result.setCode(-1);
      result.setMsg("支付插件不存在!");
      return result;
    }
    PayBack back = pay.pay(payinfo);
    return back;
  }

  public static String getNonceStr() {
    return UUID.randomUUID().toString().replace("-", "").toLowerCase();
  }

  public static String getOrderNo() {
    SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
    AdaptiveRandomWordFactory f = new AdaptiveRandomWordFactory();
    f.setMinLength(8);
    f.setMaxLength(8);
    f.setCharacters("1234567890");
    return format.format(new Date()) + "" + f.getNextWord();
  }


  @Override
  public WeiXinPaySimple handle(PayBack back) {
    WeiXinPaySimple result = new WeiXinPaySimple();
    String key = keys.get(back.getPayType());
    PaymentPlugin pay = paymentPluginMap.get(key);
    if (pay == null) {
      return result;
    }
    result = pay.handle(back);
    return result;
  }
}
